<?php

/*
	Class: Commerce_Common

	About: Author
		Tyler Vigeant

	About: License
		<http://communit.as/docs/license>
*/
class Commerce_Common {

	static function categoryTree( $root=false, $storeView=false, $parentId=false ) {
		$Catalog = new CommerceMagentoCatalog();
		
		if(empty($parentId)){
			$parentId = $Catalog->getCurrentSeasonId( $storeView );
		}
		
		$tree = $Catalog->getCategoryTree( $parentId, $storeView );
		if ($root == false && is_array($tree)) {
			for ($x = 0; $x < count($tree); $x++) {
				if ($tree[$x]['level'] == Cts_Registry::get('magento_root_catalog_level') && !empty($tree[$x]['children'])) {
					$tree = $tree[$x]['children'];
					$x = 0;
				} else {
					break;
				}
			}
		}
		return $tree;
	}

	static function getSeasons( $storeView=false ) {
		return Commerce_Common::categoryTree( true, $storeView, 1 );
	}
	
	static function getSimpleTree($tree = false, $root = false) {
		if (!is_array($tree)) {
			$tree = Commerce_Common::categoryTree($root);
		}
		if (is_array($tree)) {
			$categories = array();
			foreach ($tree as $cat) {
				$categories[ $cat['category_id'] ] = array('name' => $cat['name'], 'parent_id' => $cat['parent_id']);
				if (is_array($cat['children']) && !empty($cat['children'])) {
					$children = Commerce_Common::getSimpleTree($cat['children'], $root);
					$categories = Commerce_Common::simple_array_merge($categories, $children);
				}
			}
		}
		return $categories;
	}
	
	static function _simpleTreeParent( $id, $simple_tree ){
		$return = '';
		
		if( array_key_exists($id, $simple_tree) ){
			if( !empty($simple_tree[$id]['parent_id']) && array_key_exists($simple_tree[$id]['parent_id'], $simple_tree) ){
				$return .= Commerce_Common::_simpleTreeParent( $simple_tree[$id]['parent_id'], $simple_tree );
			}
			
			$return .= $simple_tree[$id]['name'].Cts_Registry::get('category_separator');
		}
		
		return $return;
	}
	
	static function categoryTree_to_Options( $tree=false, $root=false ){
		if(!is_array($tree)){
			$tree = Commerce_Common::categoryTree( $root );
		}
		
		$options = array();
		$simple_tree = Commerce_Common::getSimpleTree( $tree, $root );
		
		foreach( $simple_tree as $id=>$cat ){
			$options[$id] = Commerce_Common::_simpleTreeParent( $cat['parent_id'], $simple_tree ) . $cat['name'];
		}
		
		return $options;
	}
	
	static function categoryTree_single( $category_id, $root=false ){
		$tree_options = Commerce_Common::categoryTree_to_Options( false, $root );
		return (is_array($tree_options) && array_key_exists($category_id, $tree_options)) ? $tree_options[$category_id] : false;
	}
	
	static function simple_array_merge( $one, $two ){
		foreach( $two as $key=>$value ){
			$one[$key] = $value;
		}	return $one;
	}
	
	static function getProductAttributeDetails($product_id, $storeView = 0) {
		$Catalog = new CommerceMagentoCatalog();

		$p = array();
		$product = $Catalog->getProduct( $product_id, $storeView );
		$attributes = $Catalog->getProductAttributes( $product['set'] );
		$groups = $Catalog->getProductAttributeGroups( $product['set'] );
		if( !is_null($storeView) && $storeView > 0 ) {
			$product_global = $Catalog->getProduct( $product_id, NULL );
		} else {
			## This is done that the code below for compairing locale to global values will still work if we are already accessing a global product
			$product_global = &$product;
		}

		## Set the array keys to the attribute group ID for quick searching
		if( is_array($groups) ){
			foreach( $groups as $key=>$group ){
				$groups[ $group['attribute_group_id'] ] = $group;
				unset($groups[$key]);
			}
		} else {
			throw new Exception('getProductAttributeGroups returned no results running '.__FUNCTION__.'()');
		}
	
		if( is_array($product) && is_array($product_global) ){
			$details = array(
				'id' => $product['product_id'],
				'product_id' => $product['product_id'],
				'set' => $product['set'],
				'type' => $product['type'],
				'categories' => $product['categories'],
				'websites' => $product['websites'],
				'visibility' => $product['visibility'],
			);
		} else {
			throw new Exception('getProduct returned no results running '.__FUNCTION__.'()');
		}
			
		if( is_array($attributes) ){
			foreach( $attributes as $attribute ){
				$p[ $attribute['code'] ] = $attribute;
					
				if(array_key_exists($attribute['code'], $product)){
					$p[ $attribute['code'] ]['value'] = $product[$attribute['code']];
					
					## If store scope, detect if the default value is being used, and if not, store what it is.
					if( $attribute['scope']=='store' ){
						$p[ $attribute['code'] ]['is_default'] = (!is_null($storeView) && $product[$attribute['code']] == $product_global[$attribute['code']]) ? true : false;
						$p[ $attribute['code'] ]['default_value'] = ($p[$attribute['code']]['is_default']===false) ? $product_global[$attribute['code']] : null;
					} else {
						$p[ $attribute['code'] ]['is_default'] = null;
						$p[ $attribute['code'] ]['default_value'] = null;
					}
						
					## If a select or multiselect, get the options
					if( isset($attribute['type']) && ($attribute['type']=='select' || $attribute['type']=='multiselect') ){
						$p[ $attribute['code'] ]['options'] = $Catalog->getProductAttributeOptions( $attribute['attribute_id'], $storeView );
					} else {
						$p[ $attribute['code'] ]['options'] = null;
					}
				} else {
					$p[ $attribute['code'] ]['value'] = null;
					$p[ $attribute['code'] ]['is_default'] = null;
					$p[ $attribute['code'] ]['options'] = $Catalog->getProductAttributeOptions( $attribute['attribute_id'], $storeView );
				}
				
				## Limit the attribute grouping information to the group ID of the current set
				if(!empty($attribute['grouping']) && is_array($attribute['grouping'])) {
					foreach($attribute['grouping'] as $group) {
						if(array_key_exists($group['group_id'], $groups)) {
							$groups[$group['group_id']]['attributes'][] =
								array(
									'id' => $attribute['attribute_id'],
									'code' => $attribute['code'],
									'label' => $attribute['label']
								);
							unset($p[$attribute['code']]['grouping']);
							break;
						}
					}
				}
			}
		} else {
			throw new Exception('getProductAttributes returned no results running '.__FUNCTION__.'()');
		}
		
		return array($groups, $p, $details);
	}

	static function getSimplifiedChildProduct($product_id, $storeView = null, $parent_price = false) {
		$Catalog = new CommerceMagentoCatalog();

		$product = $Catalog->getProduct( $product_id, $storeView );		//dd($product);
		$attributes = $Catalog->getProductAttributes( $product['set'] );
		
		$p = array();
		$p['product_id'] = $product_id;
		$p['sku'] = $product['sku'];
		
		if( isset($product['price']) && !empty($product['price']) ){
			$p['price'] = number_format($product['price'], 2, '.', '');
		} elseif( is_array($parent_price) ){
			$p['price'] = number_format($parent_price[0], 2, '.', '');
		} else {
			$p['price'] = '';
		}
		
		if( isset($product['special_price']) && !empty($product['special_price']) ){
			$p['special_price'] = number_format($product['special_price'], 2, '.', '');
		} elseif( is_array($parent_price)&& !empty($parent_price[1]) ){
			$p['special_price'] = number_format($parent_price[1], 2, '.', '');
		} else {
			$p['special_price'] = '';
		}
		
		$p['weight'] = number_format($product['weight'], 4, '.', '');
		
		$p['attributes'] = array();
		
		foreach( $attributes as $attribute ){
			if( ($attribute['code']=='bd_color_swatch_one' || $attribute['code']=='bd_color_swatch_two')
				 || (isset($attribute['is_configurable']) && isset($attribute['scope']) && isset($attribute['type'])
						&& $attribute['is_configurable'] && $attribute['scope']=='global'
						&& ($attribute['type']=='select' || $attribute['type']=='multiselect')
					  )
				 ){
				
				$p['attributes'][ $attribute['code'] ] = array();
				$p['attributes'][ $attribute['code'] ]['label'] = $attribute['label'];
				$p['attributes'][ $attribute['code'] ]['code'] = $attribute['code'];
				$p['attributes'][ $attribute['code'] ]['type'] = $attribute['type'];
				
				if(array_key_exists($attribute['code'], $product)){
					$p['attributes'][ $attribute['code'] ]['value'] = $product[$attribute['code']];
					$p['attributes'][ $attribute['code'] ]['value_string'] = $product[$attribute['code']];
				} else {
					$p['attributes'][ $attribute['code'] ]['value'] = '';
					$p['attributes'][ $attribute['code'] ]['value_string'] = '';
				}
				
				if( isset($attribute['type']) && ($attribute['type']=='select' || $attribute['type']=='multiselect') ){
					$options = $Catalog->getProductAttributeOptions( $attribute['attribute_id'], $storeView );
					
					if(is_array($options)){
						foreach( $options as $option ){
							if( $option['value'] == $p['attributes'][ $attribute['code'] ]['value'] ){
								$p['attributes'][ $attribute['code'] ]['value_string'] = $option['label'];
								break;
							}
						}
					}
				}
				
			} else {
				continue;
			}
			
			/*
			if(array_key_exists($attribute['code'], $product)){
				
				$p[ $attribute['code'] ]['value'] = $product[$attribute['code']];
				
				## If store scope, detect if the default value is being used, and if not, store what it is.
				if( $attribute['scope']=='store' ){
					$p[ $attribute['code'] ]['is_default'] = (!is_null($storeView) && $product[$attribute['code']] == $product_global[$attribute['code']]) ? true : false;
					$p[ $attribute['code'] ]['default_value'] = ($p[$attribute['code']]['is_default']===false) ? $product_global[$attribute['code']] : null;
				} else {
					$p[ $attribute['code'] ]['is_default'] = null;
					$p[ $attribute['code'] ]['default_value'] = null;
				}
					
				## If a select or multiselect, get the options
				if( isset($attribute['type']) && ($attribute['type']=='select' || $attribute['type']=='multiselect') ){
					$p[ $attribute['code'] ]['options'] = $Catalog->getProductAttributeOptions( $attribute['attribute_id'], $storeView );
				} else {
					$p[ $attribute['code'] ]['options'] = null;
				}
			}
			*/
		}
		
		return $p;
	}
	
	static function getAttributeSetDetails( $setId, $storeView=null ){
		$Catalog = new CommerceMagentoCatalog();
		
		$p = array();
		$attributes = $Catalog->getProductAttributes( $setId );
		$groups = $Catalog->getProductAttributeGroups( $setId );
		
		## Set the array keys to the attribute group ID for quick searching
		foreach( $groups as $key=>$group ){
			$groups[ $group['attribute_group_id'] ] = $group;
			unset($groups[$key]);
		}
		
		foreach( $attributes as $attribute ){
			$p[ $attribute['code'] ] = $attribute;
			
			if(isset($attribute['attribute_id'])) $p[ $attribute['code'] ]['options'] = $Catalog->getProductAttributeOptions( $attribute['attribute_id'], $storeView );
			
			## Limit the attribute grouping information to the group ID of the current set
			if( !empty($attribute['grouping']) && is_array($attribute['grouping']) ){
				foreach( $attribute['grouping'] as $group ){
					if( array_key_exists($group['group_id'], $groups) ){
						$groups[$group['group_id']]['attributes'][] =
							array(
								'id' => $attribute['attribute_id'],
								'code' => $attribute['code'],
								'label' => $attribute['label']
							);
						unset($p[ $attribute['code'] ]['grouping']);
						break;
					}
				}
			}
		}
		
		return array($groups, $p);
	}
	
	static function attributeSetsToOptions( $sets ){
		$options = array();
		
		foreach( $sets as $set ){
			$options[ $set['set_id'] ] = $set['name'];
		}
		
		return $options;
	}
	
	static function productTypesToOptions( $types, $limit=false ){
		$options = array();
		
		foreach( $types as $type ){
			if(is_array($limit) && !in_array($type['type'], $limit)) continue;
			$options[ $type['type'] ] = $type['label'];
		}
		
		return $options;
	}
	
	static function websitesFormatted( $websites=false ){
		if( !$websites ){
			$Catalog = new CommerceMagentoCatalog();
			$websites = $Catalog->getWebsites();
		}
		
		if( is_array($websites) ){
			$formatted = array();
			foreach($websites as $website){
				$id = $website['website_id'];
				$group_id = $website['group_id'];
				$store_id = $website['store_id'];
				
				if( !array_key_exists($id, $formatted) ){
					$formatted[$id] = array(
						'website_id' 			=> $website['website_id'],
						'code' 					=> $website['code'],
						'name' 					=> $website['name'],
						'sort_order' 			=> $website['sort_order'],
						'is_default' 			=> $website['is_default'],
						'default_group_id' 	=> $website['default_group_id'],
						'groups'					=> array(),
					);
				}
				
				if( !array_key_exists($group_id, $formatted[$id]['groups']) ){
					$formatted[$id]['groups'][ $group_id ] = array(
						'group_id'		=> $website['group_id'],
						'group_title'	=> $website['group_title'],
						'is_default' 	=> ($formatted[$id]['default_group_id']==$group_id) ? true : false,
						'stores'			=> array(),
					);
				}
				
				if( !array_key_exists($store_id, $formatted[$id]['groups'][$group_id]['stores']) ){
					$formatted[$id]['groups'][$group_id]['stores'][$store_id] = array(
						'store_id'		=> $website['store_id'],
						'store_title'	=> $website['store_title'],
					);
				}
			}
			return $formatted;
		} else {
			return false;
		}
	}
	
	static function websitesToIdArray( $websites=false ){
		if( !$websites ){
			$Catalog = new CommerceMagentoCatalog();
			$websites = $Catalog->getWebsites();
		}
		
		if( is_array($websites) ){
			$ids = array();
			foreach($websites as $website){
				if( !in_array($website['website_id'], $ids) ){
					$ids[] = $website['website_id'];
				}
			}
			return $ids;
		} else {
			return false;
		}
	}
	
	static function getDefaultStore( $websites=false ){
		if( !$websites ){
			$Catalog = new CommerceMagentoCatalog();
			$websites = $Catalog->getWebsites();
		}
		
		$formatted = Commerce_Common::websitesFormatted( $websites );
		
		foreach( $formatted as $site ){
			if( $site['is_default'] ){
				foreach( $site['groups'] as $group ){
					if( $group['is_default'] ){
						foreach( $group['stores'] as $store ){
							return $store['store_id'];
						}
					}
				}
			}
		}
	}

	/*
		Function: getThumbFromSerializedMedia
	*/
	static function getThumbFromSerializedMedia($serialized_media) {
		$tmp_media = @unserialize($serialized_media);
		if( is_array($tmp_media) ){
			for ($i=0; $i < count($tmp_media); $i++) {
				if ($tmp_media[$i]['type'] == 'img' || $tmp_media[$i]['type'] == 'image') {
					return $tmp_media[$i];
				}
			}
		} else {
			return false;
		}
	}
	
	
	static function getTemplatePrices( $prices ) {
		$prices['original_price'] = array_unique( array_merge($prices['price'],$prices['special_price']) );
		$prices['special_price'] = array_unique( $prices['special_price'] );
		$prices['final_price'] = array_unique( $prices['final_price'] );
		$prices['price'] = array_unique( $prices['price'] );
		sort($prices['original_price']);
		sort($prices['special_price']);
		sort($prices['final_price']);
		sort($prices['price']);

		$smarty_prices = array('sale'=>false);
		
		## Base price
		if( count($prices['final_price'])>1 ){
			$smarty_prices['range'] = true;
			$smarty_prices['from'] = $prices['final_price'][0];
			$smarty_prices['to'] = $prices['final_price'][ count($prices['final_price'])-1 ];
		} else {
			$prices['range'] = true;
			$smarty_prices['price'] = $prices['final_price'][0];
		}
		
		## Used for sales done via special price only
		if( $prices['special_price'][0] < $prices['price'][0] ){
			$smarty_prices['sale'] = true;
			if( count($prices['price'])>1 ){
				$smarty_prices['original_range'] = true;
				$smarty_prices['original_from'] = $prices['price'][0];
				$smarty_prices['original_to'] = $prices['price'][ count($prices['price'])-1 ];
			} else {
				$smarty_prices['original_range'] = false;
				$smarty_prices['original_price'] = $prices['price'][0];
			}
		}

		## Used for sales done via promotions or (unsupported) tier pricing
		if( $prices['final_price'][0] < $prices['original_price'][0]
		||( count($prices['final_price']) > 1
			&& $prices['final_price'][count($prices['final_price'])-1] < $prices['original_price'][count($prices['original_price'])-1]
		)  ){
			
			$the_diff = array_diff($prices['special_price'], $prices['price']);
			
			$smarty_prices['sale'] = true;
			if( count($the_diff)>1 || count($prices['price'])>1 ){
				$smarty_prices['original_range'] = true;
				$smarty_prices['original_from'] = $prices['original_price'][0];
				$smarty_prices['original_to'] = $prices['original_price'][ count($prices['original_price'])-1 ];
			} else {
				$smarty_prices['original_range'] = false;
				if( !empty($prices['special_price']) ){
					$smarty_prices['original_price'] = $prices['special_price'][0];
				} else {
					$smarty_prices['original_price'] = $prices['price'][0];
				}
			}
		}
		
		return $smarty_prices;
	}
}
